//
//  WBUserAccount.swift
//  Weibo
//
//  Created by yinbo on 2018/3/8.
//  Copyright © 2018年 yinbo. All rights reserved.
//

import UIKit
private let accountFile:NSString = "useraccount.json"

class WBUserAccount: NSObject {
    //访问令牌，所有网络请求，都基于此令牌(登录除外)
    var access_token: String?
    //用户代号
    var uid: String?
    //access_token的生命周期，单位是s(开发者5年，使用者3天)
    var expires_in: TimeInterval = 0 {
        didSet{
            expiresData = Date(timeIntervalSinceNow:expires_in)
        }

    }
    //过期日期
    var expiresData:Date?
 
    
    //用户昵称
    var screen_name:String?
 
    //用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    override var description: String{
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        guard let path = accountFile.cz_appendDocumentDir(),let data = NSData(contentsOfFile: path),let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String:AnyObject] else{
            return                                                                                                                                                                                                    
        }
        yy_modelSet(with: dict ?? [:])
//        expiresData = Date(timeIntervalSinceNow:expires_in)
        if expiresData?.compare(Date()) != .orderedDescending{
            print("账户过期")
            access_token = nil
            uid = nil
            //删除账号文件
            _ = try? FileManager.default.removeItem(atPath: path)
        }
        print("从沙盒加载用户信息\(self)")
    }
    
    func saveAccount(){
        var dict = self.yy_modelToJSONObject() as? [String:AnyObject]  ?? [:]
//        dict.removeValue(forKey: "expires_in")
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),  let fileName = accountFile.cz_appendDocumentDir() else{
            return
        }
        (data as NSData).write(toFile: fileName, atomically: true)
        print("用户账号保存成功\(fileName)")
    }
    
}
